<template>
  <div class="sms-template-list">
    <div class="page-header">
      <h2>短信模板管理</h2>
      <el-button type="primary" @click="handleAddTemplate">
        <el-icon><Plus /></el-icon>
        新增模板
      </el-button>
    </div>

    <div class="page-content">
      <!-- 搜索和筛选 -->
      <div class="search-bar">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="模板代码">
            <el-input
              v-model="searchForm.code"
              placeholder="请输入模板代码"
              style="width: 150px"
              clearable
            />
          </el-form-item>
          <el-form-item label="模板名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入模板名称"
              style="width: 150px"
              clearable
            />
          </el-form-item>
          <el-form-item label="API模板ID">
            <el-input
              v-model="searchForm.apiTemplateId"
              placeholder="请输入API模板ID"
              style="width: 150px"
              clearable
            />
          </el-form-item>
          <el-form-item label="渠道">
            <el-select v-model="searchForm.channelId" placeholder="请选择渠道" style="width: 120px" clearable>
              <el-option label="全部" value="" />
              <el-option label="阿里云短信" value="aliyun" />
              <el-option label="腾讯云短信" value="tencent" />
              <el-option label="华为云短信" value="huawei" />
              <el-option label="网易云短信" value="netease" />
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" style="width: 120px" clearable>
              <el-option label="全部" value="" />
              <el-option label="验证码" value="VERIFICATION_CODE" />
              <el-option label="通知" value="NOTICE" />
              <el-option label="营销" value="PROMOTION" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 120px" clearable>
              <el-option label="全部" value="" />
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleResetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 模板列表 -->
      <el-table :data="filteredTemplates" style="width: 100%" v-loading="loading">
        <el-table-column prop="templateCode" label="模板代码" width="150" />
        <el-table-column prop="templateName" label="模板名称" width="150" />
        <el-table-column prop="apiTemplateId" label="API模板ID" width="150" />
        <el-table-column prop="channelId" label="渠道" width="120">
          <template #default="{ row }">
            <el-tag size="small" type="info">
              {{ getChannelName(row.channelId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getTypeTagType(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="模板内容" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑模板对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="700px"
      @close="handleDialogClose"
    >
      <el-form :model="templateForm" :rules="formRules" ref="templateFormRef" label-width="120px">
        <el-form-item label="模板代码" prop="templateCode">
          <el-input v-model="templateForm.templateCode" placeholder="请输入模板代码" />
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="templateForm.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="API模板ID" prop="apiTemplateId">
          <el-input v-model="templateForm.apiTemplateId" placeholder="请输入API模板ID" />
        </el-form-item>
        <el-form-item label="渠道" prop="channelId">
          <el-select v-model="templateForm.channelId" placeholder="请选择渠道" style="width: 100%">
            <el-option label="阿里云短信" value="aliyun" />
            <el-option label="腾讯云短信" value="tencent" />
            <el-option label="华为云短信" value="huawei" />
            <el-option label="网易云短信" value="netease" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="templateForm.type" placeholder="请选择模板类型" style="width: 100%">
            <el-option label="验证码" value="VERIFICATION_CODE" />
            <el-option label="通知" value="NOTICE" />
            <el-option label="营销" value="PROMOTION" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input 
            v-model="templateForm.content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入模板内容，可使用 {变量名} 格式"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="templateForm.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="templateForm.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增模板')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const templateFormRef = ref(null)

// 搜索表单数据
const searchForm = reactive({
  code: '',
  name: '',
  apiTemplateId: '',
  channelId: '',
  type: '',
  status: ''
})

// 模板列表数据
const templates = ref([
  {
    id: 1,
    templateCode: 'SMS_REG_SUCCESS',
    templateName: '注册成功通知',
    apiTemplateId: 'SMS_123456789',
    channelId: 'aliyun',
    type: 'VERIFICATION_CODE',
    content: '恭喜您注册成功！您的账号：{username}，验证码：{code}',
    status: 'active',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-15 10:30:00',
    remark: '用户注册成功后的通知短信'
  },
  {
    id: 2,
    templateCode: 'SMS_TASK_COMPLETE',
    templateName: '任务完成通知',
    apiTemplateId: 'SMS_987654321',
    channelId: 'tencent',
    type: 'NOTICE',
    content: '您的任务 {taskName} 已完成，奖励 {reward} 已发放到您的账户',
    status: 'active',
    createTime: '2024-01-16 14:20:00',
    updateTime: '2024-01-16 14:20:00',
    remark: '任务完成后的奖励通知'
  },
  {
    id: 3,
    templateCode: 'SMS_LOGIN_CODE',
    templateName: '登录验证码',
    apiTemplateId: 'SMS_456789123',
    channelId: 'huawei',
    type: 'VERIFICATION_CODE',
    content: '您的登录验证码是：{code}，有效期5分钟，请勿泄露给他人',
    status: 'inactive',
    createTime: '2024-01-17 09:15:00',
    updateTime: '2024-01-17 09:15:00',
    remark: '用户登录时的验证码短信'
  }
])

// 表单数据
const templateForm = reactive({
  id: null,
  templateCode: '',
  templateName: '',
  apiTemplateId: '',
  channelId: '',
  type: '',
  content: '',
  status: 'active',
  remark: ''
})

// 表单验证规则
const formRules = {
  templateCode: [
    { required: true, message: '请输入模板代码', trigger: 'blur' }
  ],
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  apiTemplateId: [
    { required: true, message: '请输入API模板ID', trigger: 'blur' }
  ],
  channelId: [
    { required: true, message: '请选择渠道', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性 - 现在直接从接口获取数据，不再需要本地过滤
const filteredTemplates = computed(() => templates.value)

// 辅助函数
function getChannelName(channelId) {
  const channelMap = {
    'aliyun': '阿里云短信',
    'tencent': '腾讯云短信',
    'huawei': '华为云短信',
    'netease': '网易云短信'
  }
  return channelMap[channelId] || channelId
}

function getTypeName(type) {
  const typeMap = {
    'VERIFICATION_CODE': '验证码',
    'NOTICE': '通知',
    'PROMOTION': '营销'
  }
  return typeMap[type] || type
}

function getTypeTagType(type) {
  const typeTagMap = {
    'VERIFICATION_CODE': 'warning',
    'NOTICE': 'info',
    'PROMOTION': 'success'
  }
  return typeTagMap[type] || 'info'
}

// 转换类型值为接口需要的数字格式
function getTypeValue(type) {
  const typeValueMap = {
    'VERIFICATION_CODE': 1,
    'NOTICE': 2,
    'PROMOTION': 3
  }
  return typeValueMap[type] || 1
}

// 转换渠道值为接口需要的数字格式
function getChannelValue(channelId) {
  const channelValueMap = {
    'aliyun': 10,
    'tencent': 20,
    'huawei': 30,
    'netease': 40
  }
  return channelValueMap[channelId] || 10
}

// 将接口返回的渠道数字值转换为前端使用的字符串值
function getChannelKey(channelValue) {
  const channelKeyMap = {
    10: 'aliyun',
    20: 'tencent',
    30: 'huawei',
    40: 'netease'
  }
  return channelKeyMap[channelValue] || 'aliyun'
}

// 将接口返回的类型数字值转换为前端使用的字符串值
function getTypeKey(typeValue) {
  const typeKeyMap = {
    1: 'VERIFICATION_CODE',
    2: 'NOTICE',
    3: 'PROMOTION'
  }
  return typeKeyMap[typeValue] || 'VERIFICATION_CODE'
}

// 方法
function handleSearch() {
  currentPage.value = 1
  handleRefresh()
}

function handleResetSearch() {
  Object.assign(searchForm, {
    code: '',
    name: '',
    apiTemplateId: '',
    channelId: '',
    type: '',
    status: ''
  })
  currentPage.value = 1
  handleRefresh()
}

async function handleRefresh() {
  loading.value = true
  try {
    // 构建查询参数
    const params = new URLSearchParams({
      pageSize: pageSize.value.toString(),
      pageIndex: currentPage.value.toString(),
      orderBy: '',
      orderDirection: ''
    })
    
    // 添加搜索条件，只添加非空值
    if (searchForm.code) params.append('code', searchForm.code)
    if (searchForm.name) params.append('name', searchForm.name)
    if (searchForm.apiTemplateId) params.append('apiTemplateId', searchForm.apiTemplateId)
    if (searchForm.channelId) params.append('channelId', getChannelValue(searchForm.channelId).toString())
    if (searchForm.type) params.append('type', getTypeValue(searchForm.type).toString())
    if (searchForm.status) {
      const statusValue = searchForm.status === 'active' ? 1 : 0
      params.append('status', statusValue.toString())
    }

    const res = await fetch(`/api/system/sms-template/page?${params.toString()}`, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    })
    
    const data = await res.json()
    if (data && data.success) {
      templates.value = (data.data || []).map(item => ({
        id: item.id,
        templateCode: item.code,
        templateName: item.name,
        apiTemplateId: item.apiTemplateId,
        channelId: getChannelKey(item.channelId),
        type: getTypeKey(item.type),
        content: item.content,
        status: item.status === 1 ? 'active' : 'inactive',
        remark: item.remark
      }))
      total.value = data.totalCount || 0
    } else {
      templates.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

function handleAddTemplate() {
  dialogTitle.value = '新增模板'
  resetForm()
  dialogVisible.value = true
}

function handleEdit(row) {
  dialogTitle.value = '编辑模板'
  // 只复制表单中定义的字段，避免响应式问题
  templateForm.id = row.id
  templateForm.templateCode = row.templateCode
  templateForm.templateName = row.templateName
  templateForm.apiTemplateId = row.apiTemplateId
  templateForm.channelId = row.channelId
  templateForm.type = row.type
  templateForm.content = row.content
  templateForm.status = row.status
  templateForm.remark = row.remark
  dialogVisible.value = true
}



async function handleDelete(row) {
  ElMessageBox.confirm(
    `确定要删除模板 "${row.templateName}" 吗？此操作不可恢复！`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await fetch(`/api/system/sms-template/delete?id=${row.id}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' }
      })

      const data = await res.json()
      
      if (data && data.success) {
        ElMessage.success('删除成功')
        // 刷新列表
        handleRefresh()
      } else {
        ElMessage.error('删除失败：' + (data && data.errMessage ? data.errMessage : '未知错误'))
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

async function handleSave() {
  templateFormRef.value?.validate(async (valid) => {
    if (valid) {
      saving.value = true
      
      try {
        // 转换表单数据为接口要求的格式
        const requestData = {
          type: getTypeValue(templateForm.type),
          status: templateForm.status === 'active' ? 1 : 0,
          code: templateForm.templateCode,
          name: templateForm.templateName,
          content: templateForm.content,
          remark: templateForm.remark,
          apiTemplateId: templateForm.apiTemplateId,
          channelId: getChannelValue(templateForm.channelId)
        }

        let res, data
        
        if (templateForm.id) {
          // 编辑模式 - 调用更新接口
          requestData.id = templateForm.id
          res = await fetch('/api/system/sms-template/update', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestData)
          })
          data = await res.json()
          
          if (data && data.success) {
            ElMessage.success('更新成功')
            dialogVisible.value = false
            // 刷新列表
            handleRefresh()
          } else {
            ElMessage.error('更新失败：' + (data && data.errMessage ? data.errMessage : '未知错误'))
          }
        } else {
          // 新增模式 - 调用创建接口
          res = await fetch('/api/system/sms-template/create', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestData)
          })
          data = await res.json()
          
          if (data && data.success) {
            ElMessage.success('创建成功')
            dialogVisible.value = false
            // 刷新列表
            handleRefresh()
          } else {
            ElMessage.error('创建失败：' + (data && data.errMessage ? data.errMessage : '未知错误'))
          }
        }
      } catch (error) {
        console.error('API调用失败:', error)
        ElMessage.error('接口请求失败，请检查网络连接')
      } finally {
        saving.value = false
      }
    }
  })
}

function handleDialogClose() {
  resetForm()
}

function resetForm() {
  Object.assign(templateForm, {
    id: null,
    templateCode: '',
    templateName: '',
    apiTemplateId: '',
    channelId: '',
    type: '',
    content: '',
    status: 'active',
    remark: ''
  })
  templateFormRef.value?.clearValidate()
}

function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
  handleRefresh()
}

function handleCurrentChange(val) {
  currentPage.value = val
  handleRefresh()
}

onMounted(() => {
  handleRefresh()
})
</script>

<style scoped>
.sms-template-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.page-header h2 {
  margin: 0;
  color: #1f2937;
  font-size: 24px;
  font-weight: 600;
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.search-form .el-form-item {
  margin-bottom: 12px;
  margin-right: 16px;
}

.search-form .el-form-item__label {
  font-weight: 500;
  color: #495057;
  font-size: 14px;
}

.page-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f9fafb;
  color: #374151;
  font-weight: 600;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}
</style> 